package com.dbq.fast.common.base;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.me.bean.VersionBean;
import com.dbq.fast.business.product.dialog.PayAndLoginStatusDialog;
import com.dbq.fast.business.setting.UpdateDialog;
import com.dbq.fast.business.setting.UpdateLogic;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.util.FitBottomNavUtil;
import com.dbq.fast.util.ProgressDialogUtil;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.processors.FlowableProcessor;


/**
 * Created by sunkai on 2017/10/24.
 */

public class BaseActivity extends AppCompatActivity {
    private static final SimpleDateFormat logDataFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    public boolean isResume;
    private int showEventInfoState;
    FlowableProcessor<String> logListener;

    private int logViewHeight;
    protected static UpdateLogic updateLogic;
    private boolean clickUpdate = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.hide();
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        super.onCreate(savedInstanceState);
        new FitBottomNavUtil().assistActivity(this, findViewById(android.R.id.content));
        intListener();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        logViewHeight = (metric.heightPixels / 4) * 3;
        if (getClass().getSimpleName().equals("MainActivity") ||//
                getClass().getSimpleName().equals("SettingActivity")) {
            updateLogic = new UpdateLogic(this);//初始化更新逻辑
            updateLogic.setOnUpdateListener(new UpdateLogic.OnUpdateListener() {
                @Override
                public void update(VersionBean versionBean) {
                    Log.i("versionBean", versionBean.toString());
                    runOnUiThread(() -> updateDialog(versionBean));
                }

                @Override
                public void downComplete(VersionBean versionBean) {
                    if (clickUpdate) {
                        runOnUiThread(() -> ProgressDialogUtil.hideProgress());
                        updateLogic.installApk();
                        clickUpdate = false;
                    }
                }

                @Override
                public void onPercent(long part, long total) {
                    if (clickUpdate && isResume) {
                        int percent = (int) (Double.parseDouble(String.valueOf(part)) / Double.parseDouble(String.valueOf(total)) * 100);
                        try {
                            Message message = downloadPercentHandler.obtainMessage();
                            message.what = 1;
                            message.obj = String.valueOf(percent);
                            downloadPercentHandler.sendMessage(message);
                        } catch (Exception e) {

                        }
                    }


                }

                @Override
                public void downError() {
                    runOnUiThread(() -> {
                        if (clickUpdate) {
                            ProgressDialogUtil.hideProgress();
                            Toast.makeText(BaseActivity.this, "下载失败，请检查网络", Toast.LENGTH_LONG).show();
                        }
                    });

                }

                @Override
                public void isLastVersion() {
                    lastVersion();
                }
            });
            updateLogic.autoDownloadApk();
        }
    }

    private Handler downloadPercentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    ProgressDialogUtil.update("下载进度为：" + msg.obj + "%");
                    break;
            }

        }
    };

    private void intListener() {
        logListener = RxBus.get().register(Constants.RXBUG_LOG, String.class);
        logListener.onBackpressureBuffer().observeOn(AndroidSchedulers.mainThread()).subscribe(s -> {
            showLog(s);
        });
    }

    private void showLog(String log) {
        if (findViewById(R.id.debug_view) != null) {
            TextView textView = (TextView) findViewById(R.id.debug_view);
            textView.append("\n");
            textView.append(logDataFormat.format(new Date()).toString() + " -> ");
            textView.append(log);

            if ((textView.getLineHeight() * textView.getLineCount()) > logViewHeight) {
                textView.scrollBy(0, textView.getLineHeight());
            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (event.getRepeatCount() == 0) {
                showEventInfoState++;
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (showEventInfoState == 2) {
                toggle();
            }
            if (event.getRepeatCount() == 0) {
                showEventInfoState = 0;
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    private synchronized void toggle() {
        ViewGroup viewGroup = (ViewGroup) findViewById(android.R.id.content);
        TextView textView;
        if ((textView = (TextView) viewGroup.findViewById(R.id.debug_view)) == null) {
            textView = new TextView(getApplicationContext());
            textView.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            textView.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            textView.setTextColor(0xFF_FF_FF_FF);
            textView.setBackgroundColor(0xB3_00_00_00);
            textView.setTextSize(15);
            textView.setPadding(20, 20, 20, 20);
            textView.setId(R.id.debug_view);
            viewGroup.addView(textView);
            textView.setVisibility(View.GONE);
        }
        if (textView.getVisibility() == View.GONE) {
            textView.setVisibility(View.VISIBLE);
            textView.setText("\n\n同时按下音量加减键，关闭调试信息");
            String id = User.getInstance().isLogin() ? User.getInstance().getAccount() : "请登录";
            textView.append("\n");
            textView.append("当前用户Id: " + id);
            textView.append("\n");
        } else {
            textView.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        YibaAnalysis.getInstance().onResume(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        YibaAnalysis.getInstance().onPause(this);
    }


    /**
     * 更新界面，在很多地方都可能弹出
     *
     * @param versionBean
     */

    private boolean isShowing = false;

    protected void updateDialog(VersionBean versionBean) {
        if (isShowing) return;
        //判断是否需要更新
        if (versionBean.isUpdate.equals("0")) {
            isShowing = true;
            UpdateDialog.show(getSupportFragmentManager(),//
                    PayAndLoginStatusDialog.UPDATE_VERSION,//
                    versionBean.updateContent, versionBean.version)//
                    .setUpdateListener(new UpdateDialog.OnUpdateListener() {
                        @Override
                        public void nextPage() {
                            clickUpdate = true;
                            //TODO 跳转到安装界面
                            boolean installStatus = updateLogic.installApk();
                            if (!installStatus && isResume) { //存在 ->  安装
                                ProgressDialogUtil.showProgress(BaseActivity.this, "", "下载中...");
                                updateLogic.handleDownloadApk();

                            }
                            YibaAnalysis.getInstance().event(BaseActivity.this, EventConstant.DIALOG_UPDATE);
                            isShowing = false;
                        }

                        @Override
                        public void cancel() {
                            YibaAnalysis.getInstance().event(BaseActivity.this, EventConstant.CANCEL_UPDATE);
                            isShowing = false;
                            lastVersion();
                        }
                    });
        } else {
            Toast.makeText(this, "已经是最新版本了", Toast.LENGTH_LONG).show();
        }
    }


    protected void lastVersion() {

    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(Constants.RXBUG_LOG, logListener);
        super.onDestroy();
    }

}
